package com.ikingtech.framework.sdk.pay.embedded.supplier.ali;

import com.alipay.v3.ApiClient;
import com.alipay.v3.ApiException;
import com.alipay.v3.Configuration;
import com.alipay.v3.util.model.AlipayConfig;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.enums.pay.CashierSupplierEnum;
import com.ikingtech.framework.sdk.pay.embedded.supplier.*;
import com.ikingtech.framework.sdk.pay.embedded.supplier.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tie yan
 */
public class AliCashier extends AbstractCashier {

    private static final Map<String, ApiClient> MERCHANT_CONFIG = new ConcurrentHashMap<>();

    @Override
    public PayOrder pay(PayArgs args) {
        this.setConfig();
        switch (args.getPayType()) {
            case ALI_PAY_JS:
            case ALI_PAY_SCAN:
            case ALI_PAY_APP:
            default:
                throw new FrameworkException("暂不支持");
        }
    }

    @Override
    public CancelResult cancel(CancelArgs args) {
        throw new FrameworkException("暂不支持");
    }

    @Override
    public RefundResult refund(RefundArgs args) {
        throw new FrameworkException("暂不支持");
    }

    @Override
    public RedPackResult redPack(RedPackArgs request) {
        throw new FrameworkException("暂不支持");
    }

    @Override
    public RedPackResult readPackConfirm(RedPackArgs args) {
        throw new FrameworkException("暂不支持");
    }

    @Override
    public PayResult validate(String resultParam, Map<String, Object> resultParamMap) {
        throw new FrameworkException("暂不支持");
    }

    @Override
    public CashierSupplierEnum supplier() {
        return CashierSupplierEnum.ALI_PAY;
    }

    @Override
    public PayResult getPayResult(GetPayResultArgs args) {
        throw new FrameworkException("暂不支持");
    }

    public void setConfig() {
        if (!MERCHANT_CONFIG.containsKey(this.config.getAppId())) {
            ApiClient client = Configuration.getDefaultApiClient();
            AlipayConfig config = new AlipayConfig();
            config.setAppId(this.config.getAppId());
            config.setPrivateKey(this.config.getPrivateKey());
            config.setAlipayPublicKey(this.config.getPublicKey());
            try {
                client.setAlipayConfig(config);
                MERCHANT_CONFIG.put(this.config.getAppId(), client);
            }  catch (ApiException e) {
                throw new FrameworkException("支付宝支付失败[创建配置异常]");
            }
        }
    }
}
